package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DateTimeEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.ChangeRuleStatusDTO;
import com.xbongbong.paas.pojo.dto.TransferBackRuleSeniorSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.PublicSeasSeniorTabEnum;
import com.xbongbong.pro.enums.errorcodes.PublicPoolErrorCodeEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorDeleteDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorMoveDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorSaveDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.TransferBackRuleSeniorEntity;
import com.xbongbong.saas.enums.ClueRuleEnum;
import com.xbongbong.saas.enums.ClueSeniorBackChildEnum;
import com.xbongbong.saas.enums.ClueSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.CustomerChildTypeEnum;
import com.xbongbong.saas.enums.CustomerRuleEnum;
import com.xbongbong.saas.enums.CustomerSeniorBackChildEnum;
import com.xbongbong.saas.enums.CustomerSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SeniorRuleValueEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.factory.publicrule.OperateSeniorBackRuleValue;
import com.xbongbong.saas.factory.publicrule.OperateSeniorOtherSetRuleValue;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.RoleModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @author: 杨磊
 * @date: 公海高级模式日志
 * @since v1.0
 */
@Component
public class PublicSeniorLogHelp {

    private static final Logger LOG = LoggerFactory.getLogger(PublicSeniorLogHelp.class);

    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private LabelModel labelModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private RoleModel roleModel;
    @Resource
    private OperateSeniorBackRuleValue operateRuleValue;
    @Resource
    private OperateSeniorOtherSetRuleValue otherSetRuleValue;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private CommonHelp commonHelp;
    /**
     * 公海池规则保存时的日志保存
     *
     * @param oldEntity 修改之前的实体
     * @param newEntity 修改之后的实体
     * @param seniorSaveDTO 前端传参
     * @param type 规则类型
     * @throws XbbException
     */
    public void savePublicRuleLog(TransferBackRuleSeniorEntity oldEntity, TransferBackRuleSeniorEntity newEntity, TransferBackRuleSeniorSaveDTO seniorSaveDTO,Integer type) throws XbbException {
        if (newEntity == null) {
            LOG.error("新公海规则为空");
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218005);
        }
        String loginUserName = seniorSaveDTO.getLoginUserName();
        Long formId = seniorSaveDTO.getFormId();
        String corpid = seniorSaveDTO.getCorpid();
        Integer businessType = seniorSaveDTO.getBusinessType();
        String userId = seniorSaveDTO.getUserId();
        String httpHeader = seniorSaveDTO.getHttpHeader();
        if (type <= CustomerSeniorRuleTypeEnum.BACK_RULE.getCode()) {
            PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId,corpid);
            Map<String, FieldAttrEntity> explainMap = Objects.nonNull(paasFormExplainEntity) ? ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains()) : new HashMap<>();
            //自动退回、自动转移规则操作日志封装
            backAndTransferLogMemo(explainMap,oldEntity,newEntity,loginUserName,paasForm.getName(),corpid,businessType,type,userId,httpHeader);
        } else {
            //最大线索（客户）数、前负责人、捞取频率规则的操作日志封装
            otherSetRuleLogMemo(oldEntity,newEntity,loginUserName,corpid,businessType,type,userId,httpHeader);
        }
    }

    /**
     * 自动退回、自动转移的规则操作日志封装
     * @param explainMap 表单模板
     * @param oldEntity 修改之前的实体
     * @param newEntity 修改之后的实体
     * @param loginUserName 登录人
     * @param formName 当前表单名称
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param type 规则类型
     * @param userId 用户id
     * @param httpHeader ip
     * @throws XbbException
     */
    public void backAndTransferLogMemo(Map<String, FieldAttrEntity> explainMap, TransferBackRuleSeniorEntity oldEntity, TransferBackRuleSeniorEntity newEntity, String loginUserName,String formName,String corpid,Integer businessType,
                                       Integer type,String userId,String httpHeader) throws XbbException {
        OperateTypeEnum operateTypeEnum = null;
        String logMemo = "";
        if (Objects.equals(type, CustomerSeniorRuleTypeEnum.BACK_RULE.getCode())){
            logMemo = LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_BACK;
        }else if (Objects.equals(type, CustomerSeniorRuleTypeEnum.TRANSFER_RULE.getCode())){
            logMemo = LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_TRANSFER;
        }
        // 公海池规则
        JSONArray oldJsonData = oldEntity.getJsonData();
        JSONArray newJsonData = newEntity.getJsonData();
        JSONArray oldRuleValue = oldEntity.getRuleValue();
        JSONArray newRuleValue = newEntity.getRuleValue();
        String memo = "";
        List<DetailLogPojo> detailArr = new ArrayList<>();
        if (oldRuleValue == null ){
            operateTypeEnum = OperateTypeEnum.EDIT;
            memo = String.format(I18nMessageUtil.getMessage(logMemo), loginUserName,OperateTypeEnum.EDIT.getName(),OperateModuleTypeEnum.OpenSeaRules.getName(),formName);
        }else {
            operateTypeEnum = OperateTypeEnum.EDIT;
            //规则名称
            String oldRuleNameStr = operateRuleValue.getRuleNameStr(oldRuleValue);
            String newRuleNameStr = operateRuleValue.getRuleNameStr(newRuleValue);
            //适用范围
            String oldApplyScore = operateRuleValue.getApplyScore(oldRuleValue);
            String newApplyScore = operateRuleValue.getApplyScore(newRuleValue);
            //不退回选择的筛选条件
//        String oldJsonDataStr = jsonDataCondition(explainMap, oldJsonData, corpid,businessType);
//        String newJsonDataStr = jsonDataCondition(explainMap, newJsonData, corpid,businessType);
            //退回选择的筛选条件
            JSONArray oldFilterRuleArr = operateRuleValue.getFilterRuleArr(oldRuleValue);
            JSONArray newFilterRuleArr = operateRuleValue.getFilterRuleArr(newRuleValue);
            String oldFilterStr = jsonDataCondition(explainMap, oldFilterRuleArr, corpid,businessType);
            String newFilterStr = jsonDataCondition(explainMap, newFilterRuleArr, corpid,businessType);
            //触发条件
            String oldTriggerScreenStr = triggerScreenCondition(oldRuleValue, businessType,corpid);
            String newTriggerScreenStr = triggerScreenCondition(newRuleValue, businessType,corpid);
            //目标公海
            String oldObjectGroupStr = operateRuleValue.getObjectGroup(oldRuleValue);
            String newObjectGroupStr = operateRuleValue.getObjectGroup(newRuleValue);

            //更新时间
            SimpleDateFormat SDF = new SimpleDateFormat(DateTimeEnum.DATETIME.getType());
            String oldUpdateTime = DateTimeUtil.getStringEpochSecond(oldEntity.getUpdateTime(), SDF);;
            String newUpdateTime = DateTimeUtil.getStringEpochSecond(DateTimeUtil.getInt(), SDF);;


            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.PUBLIC_RULE_NAME.getName(), oldRuleNameStr,newRuleNameStr));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.APPLY_SCOPE.getName(),oldApplyScore ,newApplyScore));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.FILTER_SCREEN.getName(), oldFilterStr,newFilterStr));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.TRIGGER_SCREEN.getName(), oldTriggerScreenStr,newTriggerScreenStr));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.OBJECT_GROUP.getName(), oldObjectGroupStr,newObjectGroupStr));
            detailArr.add(new DetailLogPojo(I18nMessageUtil.getMessage(CommonConstant.UPDATE_TIME), oldUpdateTime,newUpdateTime));

            memo = String.format(I18nMessageUtil.getMessage(logMemo), loginUserName,OperateTypeEnum.EDIT.getName(),OperateModuleTypeEnum.OpenSeaRules.getName(),formName);
        }
        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, loginUserName, OperateModuleTypeEnum.OpenSeaRules,operateTypeEnum,
                null, OperateModuleTypeEnum.OpenSeaRules.getName(), memo, httpHeader);
    }

    /**
     * 最大线索（客户）数、前负责人、捞取频率规则的操作日志封装
     * @param oldEntity 修改之前的实体
     * @param newEntity 修改之后的实体
     * @param loginUserName 登录人名称
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param type 规则类型
     * @param userId 登录人id
     * @param httpHeader ip
     * @throws XbbException
     */
    public void otherSetRuleLogMemo(TransferBackRuleSeniorEntity oldEntity, TransferBackRuleSeniorEntity newEntity, String loginUserName,
                                       String corpid,Integer businessType,Integer type,String userId,String httpHeader) throws XbbException {
        JSONObject oldRuleValue = oldEntity.getRuleValue().getJSONObject(BasicConstant.ZERO);
        JSONObject newRuleValue = newEntity.getRuleValue().getJSONObject(BasicConstant.ZERO);
        List<Long> oldLabelIds = null;
        oldLabelIds = otherSetRuleValue.getCustomerLabelIds(oldRuleValue);
        Integer oldStatus = otherSetRuleValue.getStatus(oldEntity);
        Integer oldContract = otherSetRuleValue.getContract(oldRuleValue);
        Integer oldOpportunity = otherSetRuleValue.getOpportunity(oldRuleValue);
        JSONArray oldCustomerStatusArray = otherSetRuleValue.getCustomerStatus(oldRuleValue,businessType);
        Integer oldType = otherSetRuleValue.getType(oldRuleValue);
        JSONArray oldRestrict = otherSetRuleValue.getRestrict(oldEntity);
        Integer newStatus = otherSetRuleValue.getStatus(newEntity);
        Integer newContract = otherSetRuleValue.getContract(newRuleValue);
        Integer newOpportunity = otherSetRuleValue.getOpportunity(newRuleValue);
        JSONArray newCustomerStatusArray = otherSetRuleValue.getCustomerStatus(newRuleValue,businessType);
        Integer newType = otherSetRuleValue.getType(newRuleValue);
        JSONArray newRestrict = otherSetRuleValue.getRestrict(newEntity);
        List<Long> newLabelIds = otherSetRuleValue.getCustomerLabelIds(newRuleValue);
        JSONObject oldBackRule = null;
        JSONObject newBackRule = null;
        if (Objects.equals(type, CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode())) {
            oldBackRule = otherSetRuleValue.getBackRule(oldRuleValue);
            newBackRule = otherSetRuleValue.getBackRule(newRuleValue);
        }
        // 数据字典项：获取客户状态
        Map<String, String> statusMap = dataDictionaryModel.getDictionaryMap(DictionaryEnum.CUSTOMER_STATUS, corpid, null);
        // 公海池规则名称
        String opObjectName = CustomerSeniorRuleTypeEnum.getByCode(type).getName();
        String notUserStatus = LogMemoConstant.LOG_MEMO_USER_NOT_CUSTOMER_STATUS_RULE;
        String userStatus = LogMemoConstant.LOG_MEMO_USER_CUSTOMER_STATUS_RULE;
        String maxUpdateLog = LogMemoConstant.LOG_MEMO_USER_UPDATE_MAX_CUSTOMER_BACK_RULE;
        if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            opObjectName = ClueSeniorRuleTypeEnum.getByCode(type).getName();
            statusMap = ClueStatusEnum.getCodeAndNameMap();
            notUserStatus = LogMemoConstant.LOG_MEMO_USER_NOT_CLUE_STATUS_RULE;
            userStatus = LogMemoConstant.LOG_MEMO_USER_CLUE_STATUS_RULE;
            maxUpdateLog = LogMemoConstant.LOG_MEMO_USER_UPDATE_MAX_CLUE_BACK_RULE;
        }
        String defaultMemo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_CUSTOMER_RULE), loginUserName, opObjectName);

        OperateTypeEnum operateTypeEnum = OperateTypeEnum.EDIT;
        // 是否启用或关闭某种规则
        String isOpenRule = null;
        if (!Objects.equals(newStatus, oldStatus)) {
            if (Objects.equals(newStatus, 0)) {
                operateTypeEnum = OperateTypeEnum.CLOSE;
                // 操作类型标识
                isOpenRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_CLOSE_CUSTOMER_RULE), opObjectName);
            } else {
                operateTypeEnum = OperateTypeEnum.ENABLE;
                // 操作类型标识
                isOpenRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_OPEN_CUSTOMER_RULE), opObjectName);
            }
        }
        // 标签变化
        String changLabel = null;
        if(CollectionUtils.isNotEmpty(oldLabelIds) || CollectionUtils.isNotEmpty(newLabelIds)) {
            List<String> labelListOld = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<String> labelIdListNew = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            String oldStr = "";
            String newStr = "";
            if(oldLabelIds.size() > 0){
                List<LabelEntity> labelEntityList = labelModel.getByLabelIds(oldLabelIds, corpid);
                labelEntityList.forEach(labelEntity -> labelListOld.add(labelEntity.getName()));
                oldStr = StringUtils.join(labelListOld, "，");
            }
            if(newLabelIds.size() > 0){
                List<LabelEntity> labelEntityList = labelModel.getByLabelIds(newLabelIds, corpid);
                labelEntityList.forEach(labelEntity -> labelIdListNew.add(labelEntity.getName()));
                newStr = StringUtils.join(labelIdListNew, "，");
            }
            if(oldStr != "" || newStr != ""){
                changLabel = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_LABEL_RULE), oldStr, newStr);
            }
        }
        // 是否取消设置公海池规则不包含有合同的客户
        String setTingContractRule = null;
        if (!Objects.equals(newContract, oldContract)) {
            if (Objects.equals(newContract, 0)) {
                setTingContractRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CANCEL_SETTING_CONTRACT_RULE), opObjectName);
            } else {
                setTingContractRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SETTING_CONTRACT_RULE), opObjectName);
            }
        }
        // 是否取消设置公海池规则不包含有销售机会的客户。
        String setTingOpportunityRule = null;
        if (!Objects.equals(newOpportunity, oldOpportunity)) {
            if (Objects.equals(newOpportunity, 0)) {
                setTingOpportunityRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CANCEL_SETTING_OPPORTUNITY_RULE), opObjectName);
            } else {
                setTingOpportunityRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SETTING_OPPORTUNITY_RULE), opObjectName);
            }
        }
        // 设置是不包含的客户状态
        String notStatusRule = null;
        if (!Objects.equals(newCustomerStatusArray, oldCustomerStatusArray)) {
            if (newCustomerStatusArray.size() == 0) {
                notStatusRule = String.format(I18nMessageUtil.getMessage(notUserStatus), opObjectName);
            } else {
                StringBuilder statusStr = new StringBuilder();
                for (Object statusObject : newCustomerStatusArray) {
                    String statusInt = (String) statusObject;
                    statusStr.append(" " + statusMap.get(statusInt));
                }
                notStatusRule = String.format(I18nMessageUtil.getMessage(userStatus), opObjectName, statusStr.toString());
            }
        }
        // 编辑设置
        String updateRule = null;
        if (!Objects.equals(newType, oldType)) {
            CustomerChildTypeEnum childCustomerRule = CustomerChildTypeEnum.getChildTypeByCode(newType);
            if (childCustomerRule != CustomerChildTypeEnum.UNKNOWN) {
                updateRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_NEW_CUSTOMER_RULE), childCustomerRule.getName());
            }
        }
        // 编辑了数值设置
        String setRule = null;
        if (!Objects.equals(newRestrict, oldRestrict)) {
            setRule = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_DATE_SET));
        }
        // 编辑了超过最大客户数退回规则
        String maxBackRule = null;
        if (!Objects.equals(newBackRule, oldBackRule)) {
            maxBackRule = String.format(I18nMessageUtil.getMessage(maxUpdateLog));
        }
        StringBuilder memoStr = new StringBuilder();
        memoStr.append(defaultMemo);
        if(isOpenRule != null){
            memoStr.append(isOpenRule);
        }
        if(setTingContractRule != null){
            memoStr.append(setTingContractRule);
        }
        if(setTingOpportunityRule != null){
            memoStr.append(setTingOpportunityRule);
        }
        if(notStatusRule != null){
            memoStr.append(notStatusRule);
        }
        if(updateRule != null){
            memoStr.append(updateRule);
        }
        if(setRule != null){
            memoStr.append(setRule);
        }
        if(maxBackRule != null){
            memoStr.append(maxBackRule);
        }
        if(changLabel != null){
            memoStr.append(changLabel);
        }
        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.OpenSeaRules,operateTypeEnum, newEntity.getId().toString(), OperateModuleTypeEnum.OpenSeaRules.getName(), memoStr.toString(), httpHeader);
    }
    /**
     * 公海池分组保存时的日志保存
     *
     * @param oldEntity  修改之前的实体
     * @param newEntity 修改之后的实体
     * @param seniorSaveDTO 前端传参
     * @param isNew 是否新建
     * @throws XbbException
     */
    public void savePublicGroupLog(PublicGroupSeniorEntity oldEntity, PublicGroupSeniorEntity newEntity, PublicGroupSeniorSaveDTO seniorSaveDTO, boolean isNew) throws XbbException {
        String loginUserName = seniorSaveDTO.getLoginUserName();
        Long formId = seniorSaveDTO.getFormId();
        String corpid = seniorSaveDTO.getCorpid();
        Integer businessType = seniorSaveDTO.getBusinessType();
        PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId,corpid);
        Map<String, FieldAttrEntity> explainMap = null;
        if (Objects.nonNull(paasFormExplainEntity)){
            explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
        }
        OperateModuleTypeEnum operateModuleTypeEnum =  OperateModuleTypeEnum.CUSTOMER_PUBLIC;
        if(Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            operateModuleTypeEnum = OperateModuleTypeEnum.CLUE_PUBLIC;
        }
        OperateTypeEnum operateTypeEnum = null;
        String memo = "";
        //分组名称
        String oldNameStr = oldEntity.getName();
        List<DetailLogPojo> detailArr = new ArrayList<>();
        if (isNew){
            operateTypeEnum = OperateTypeEnum.NEW;
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_GROUP),
                    loginUserName,OperateTypeEnum.NEW.getName(),operateModuleTypeEnum.getName(),paasForm.getName(),oldNameStr);
        }else {
            String newNameStr = newEntity.getName();
            operateTypeEnum = OperateTypeEnum.EDIT;
            //管理员
            String oldAdminStr = getPublicGroupAdminUsers(oldEntity.getAdminScopeRule());
            String newAdminStr = getPublicGroupAdminUsers(newEntity.getAdminScopeRule());
            //成员
            String oldUserStr = getPublicGroupAdminUsers(oldEntity.getScopeRule());
            String newUserStr = getPublicGroupAdminUsers(newEntity.getScopeRule());
            //筛选条件
            String oldJsonDataStr = jsonDataCondition(explainMap, oldEntity.getJsonData(), corpid, businessType);
            String newJsonDataStr = jsonDataCondition(explainMap, newEntity.getJsonData(), corpid, businessType);

            //更新时间
            SimpleDateFormat SDF = new SimpleDateFormat(DateTimeEnum.DATETIME.getType());
            String oldUpdateTime = DateTimeUtil.getStringEpochSecond(oldEntity.getUpdateTime(), SDF);;
            String newUpdateTime = DateTimeUtil.getStringEpochSecond(DateTimeUtil.getInt(), SDF);;

            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.PUBLIC_GROUP_NAME.getName(), oldNameStr,newNameStr));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.ADMIN_SCOPE.getName(),oldAdminStr ,newAdminStr));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.USER_SCOPE.getName(), oldUserStr,newUserStr));
            detailArr.add(new DetailLogPojo(OperateModuleTypeEnum.INTI_RULE.getName(), oldJsonDataStr,newJsonDataStr));
            detailArr.add(new DetailLogPojo(I18nMessageUtil.getMessage(CommonConstant.UPDATE_TIME), oldUpdateTime,newUpdateTime));

            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_GROUP),
                    loginUserName,OperateTypeEnum.EDIT.getName(),operateModuleTypeEnum.getName(),paasForm.getName(),oldNameStr);
        }
        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, seniorSaveDTO.getUserId(), loginUserName, operateModuleTypeEnum,operateTypeEnum,
                null, operateModuleTypeEnum.getName(), memo, seniorSaveDTO.getHttpHeader());
    }

    /**
     * 公海池分组删除日志
     *
     * @param oldEntity 删除的实体
     * @param seniorSaveDTO 前端传参
     * @throws XbbException
     */
    public void deletePublicGroupLog(PublicGroupSeniorEntity oldEntity, PublicGroupSeniorDeleteDTO seniorSaveDTO) throws XbbException {
        String loginUserName = seniorSaveDTO.getLoginUserName();
        Long formId = seniorSaveDTO.getFormId();
        String corpid = seniorSaveDTO.getCorpid();
        Integer businessType = seniorSaveDTO.getBusinessType();
        PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);
        OperateModuleTypeEnum operateModuleTypeEnum =  OperateModuleTypeEnum.CUSTOMER_PUBLIC;
        if(Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            operateModuleTypeEnum = OperateModuleTypeEnum.CLUE_PUBLIC;
        }
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_GROUP),
                loginUserName,OperateTypeEnum.DELETE.getName(),operateModuleTypeEnum.getName(),paasForm.getName(), oldEntity.getName());

        mongoLogHelp.buildLog4DetailArr(null, corpid, seniorSaveDTO.getUserId(), loginUserName, operateModuleTypeEnum,OperateTypeEnum.DELETE,
                null, operateModuleTypeEnum.getName(), memo, seniorSaveDTO.getHttpHeader());
    }

    /**
     * 移动公海分组操作日志
     *
     * @param seniorSaveDTO 前端传参
     * @throws XbbException
     */
    public void movePublicGroupLog(PublicGroupSeniorMoveDTO seniorSaveDTO) throws XbbException {
        String loginUserName = seniorSaveDTO.getLoginUserName();
        Long formId = seniorSaveDTO.getFormId();
        String corpid = seniorSaveDTO.getCorpid();
        Integer businessType = seniorSaveDTO.getBusinessType();
        PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);
        OperateModuleTypeEnum operateModuleTypeEnum =  OperateModuleTypeEnum.CUSTOMER_PUBLIC;
        if(Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            operateModuleTypeEnum = OperateModuleTypeEnum.CLUE_PUBLIC;
        }
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_GROUP_MOVE),
                loginUserName,OperateTypeEnum.EDIT.getName(),operateModuleTypeEnum.getName(),paasForm.getName());

        mongoLogHelp.buildLog4DetailArr(null, corpid, seniorSaveDTO.getUserId(), loginUserName, operateModuleTypeEnum,OperateTypeEnum.EDIT,
                null, operateModuleTypeEnum.getName(), memo, seniorSaveDTO.getHttpHeader());
    }
    /**
     * 公海高级欧式-停用启用公海操作日志
     *
     * @param ruleStatusDTO 前端传参
     * @throws XbbException
     */
    public void openAndCloseLog(ChangeRuleStatusDTO ruleStatusDTO) throws XbbException {
        String loginUserName = ruleStatusDTO.getLoginUserName();
        Long formId = ruleStatusDTO.getFormId();
        String corpid = ruleStatusDTO.getCorpid();
        Integer businessType = ruleStatusDTO.getBusinessType();
        Integer type = ruleStatusDTO.getType();
        PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);
        String formName = "";
        if (paasForm != null){
            formName = paasForm.getName();
        }
        OperateModuleTypeEnum operateModuleTypeEnum =  OperateModuleTypeEnum.CUSTOMER_PUBLIC;
        if(Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            operateModuleTypeEnum = OperateModuleTypeEnum.CLUE_PUBLIC;
        }
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.ENABLE;
        if(Objects.equals(ruleStatusDTO.getStatus(),EnableEnum.CLOSE.getCode())){
            operateTypeEnum = OperateTypeEnum.CLOSE;
        }
        String memo = "";
        PublicSeasSeniorTabEnum tabEnum = PublicSeasSeniorTabEnum.getByCode(ruleStatusDTO.getTabType());
        switch (tabEnum){
            case PUBLIC_GROUP_RULE_SET:
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_GROUP_OPEN), loginUserName, operateTypeEnum.getName(),operateModuleTypeEnum.getName(),formName);
                break;
            case PUBLIC_TRANSFER_RULE_SET:
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_TRANSFER_OPEN), loginUserName, operateTypeEnum.getName(),operateModuleTypeEnum.getName(),formName);
                break;
            case PUBLIC_BACK_RULE_SET:
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_BACK_OPEN), loginUserName, operateTypeEnum.getName(),operateModuleTypeEnum.getName(),formName);
                break;
            case PUBLIC_OTHER_RULE_SET:
                String ruleName = "";
                if (Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                    if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)){
                        ruleName = CustomerSeniorRuleTypeEnum.getByCode(type).getName();
                    }else {
                        ruleName = CustomerRuleEnum.getByCode(type).getName();
                    }
                }
                if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
                    if (commonHelp.isCluePublicPoolSeniorModel(corpid)){
                        ruleName = ClueSeniorRuleTypeEnum.getByCode(type).getName();
                    }else {
                        ruleName = ClueRuleEnum.getByCode(type).getName();
                    }
                }
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_SENIOR_OTHER_SET_OPEN), loginUserName, operateTypeEnum.getName(),operateModuleTypeEnum.getName(),ruleName);
                break;
            default:
                break;
        }
        mongoLogHelp.buildLog4DetailArr(null, corpid, ruleStatusDTO.getUserId(), loginUserName, operateModuleTypeEnum,operateTypeEnum,
                null, operateModuleTypeEnum.getName(), memo, ruleStatusDTO.getHttpHeader());
    }



    public void savePublicPoolMoDelChangeLog(String corpid, Integer businessType, String userId, String loginUserName, String modelType, String operateType, String httpHeader) throws XbbException {
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_MODEL_CHANGE), loginUserName, operateType,
                I18nMessageUtil.getMessage(MessageConstant.CUSTOMER_HIGH_SEAS_POOL),modelType);
        if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(),businessType)) {
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_PUBLIC_POOL_MODEL_CHANGE), loginUserName, operateType, I18nMessageUtil.getMessage(MessageConstant.CLUE_HIGH_SEAS_POOL),modelType);
        }

        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.OpenSeaRules, OperateTypeEnum.SET,
                null, OperateModuleTypeEnum.OpenSeaRules.getName(), memo, httpHeader);

    }


    public void saveBatchChangePublicGroup(List<PaasFormDataEntityExt> paasFormDataEntityExts, String corpid, Integer businessType, String formName, String groupName,String userId, String loginUserName, String httpHeader) throws XbbException {
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_BATCH_CHANGE_PUBLIC_GROUP), loginUserName, formName, groupName,
                paasFormDataEntityExts.size());

        OperateModuleTypeEnum operateModuleTypeEnum = OperateModuleTypeEnum.CUSTOMER;
        String attr = CustomerManagementEnum.NAME.getAttr();
        if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(),businessType)) {
            attr = ClueEnum.COMPANY_NAME.getAttr();
            operateModuleTypeEnum = OperateModuleTypeEnum.CLUE;
        }

        List<String> nameList = new ArrayList<>();
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
            JSONObject data = JSON.parseObject(paasFormDataEntityExt.getData().toJSONString());
            String name = data.getString(attr);
            nameList.add(name);
        }
        String nameStr = StringUtils.join(nameList, "，");

        List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        InfoArrPojo infoArrPojo = new InfoArrPojo();
        infoArrPojo.setContent(nameStr);
        infoArrPojoList.add(infoArrPojo);
        mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.BATCH_CHANGE_PUBLIC_GROUP,
                null, null, memo, httpHeader);

    }



    /**
     * 获取筛选条件 拼接的日志信息
     * @param explainMap 表单解释
     * @param jsonDataArr 筛选条件
     * @param corpid 公司id
     * @return
     * @throws XbbException
     */
    public String jsonDataCondition(Map<String, FieldAttrEntity> explainMap, JSONArray jsonDataArr, String corpid,Integer businessType) throws XbbException {
        // 符号
        String mark = "";
        // 字段
        String attrName = "";
        // 数据
        String data = "所有客户统一设置";
        if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            data = "所有线索统一设置";
        }
        StringBuilder conditionStr = new StringBuilder();
        for (Object o : jsonDataArr) {
            JSONObject object = JSON.parseObject(o.toString());
            if (Objects.equals(BasicConstant.ONE,object.getInteger("filterType"))){
                conditionStr.append(data).append(";");
                continue;
            }
            String symbol = object.getString("symbol");
            Integer fieldType = object.getInteger("fieldType");
            ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(symbol);
            if(conditionEnum != null){
                mark = conditionEnum.getMemo();
            }
            String attr = object.getString("attr");
            FieldAttrEntity fieldAttrEntity = null ;
            if ( !explainMap.isEmpty() ){
                fieldAttrEntity = explainMap.get(attr);
            }
            JSONArray value = object.getJSONArray("value");
            attrName = Objects.nonNull(fieldAttrEntity) ? fieldAttrEntity.getAttrName() : null;
            if (Objects.equals(attr,"province")){
                attrName = I18nMessageUtil.getMessage(CommonConstant.PROVINCE);
            }else if (Objects.equals(attr,"city")){
                attrName = I18nMessageUtil.getMessage(CommonConstant.CITY);
            }else if (Objects.equals(attr,"district")){
                attrName = I18nMessageUtil.getMessage(CommonConstant.AREA);
            }
            try{
                List<String> dataArr = JSONArray.parseArray(JSON.toJSONString(value),String.class);
                List<String> nameIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                boolean isUserField = Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr())
                        || Objects.equals(attr, CustomerManagementEnum.CREATOR_ID.getAttr())
                        || Objects.equals(attr, ClueEnum.CREATOR_ID.getAttr())
                        || Objects.equals(attr, ClueEnum.OWNER_ID.getAttr())
                        || Objects.equals(fieldType, FieldTypeEnum.USER.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType());
                if(isUserField){
                    if(CollectionUtils.isNotEmpty(dataArr)){
                        List<UserEntity> getByUserId = userModel.getByUserId(dataArr,corpid);
                        getByUserId.forEach(userEntity -> nameIn.add(userEntity.getName()));
                    }
                    data = StringUtils.join(nameIn, "，");
                } else if(Objects.equals(attr, CustomerManagementEnum.LABEL.getAttr()) || Objects.equals(attr,ClueEnum.LABEL.getAttr())){
                    List<Long> labelIdIn = JSONArray.parseArray(JSON.toJSONString(value),Long.class);
                    if(CollectionUtils.isNotEmpty(labelIdIn)){
                        List<LabelEntity> getByLabelIds = labelModel.getByLabelIds(labelIdIn,corpid);
                        getByLabelIds.forEach(labelEntity -> nameIn.add(labelEntity.getName()));
                    }
                    data = StringUtils.join(nameIn, "，");
                } else if (Objects.equals(fieldType, FieldTypeEnum.ADDTIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.UPDATETIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())){
                    List<Long> timeIn = JSONArray.parseArray(JSON.toJSONString(value),Long.class);
                    if(CollectionUtils.isNotEmpty(timeIn)){
                        for(Long time : timeIn){
                            String timeStr = DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFDate);
                            nameIn.add(timeStr);
                        }
                    }
                    data = StringUtils.join(nameIn, "，");
                } else if(Objects.equals(fieldType,FieldTypeEnum.COMBO.getType())){
                    JSONArray items = object.getJSONArray("items");
                    List<ItemPoJo> itemPoJos = JSONArray.parseArray(JSON.toJSONString(items),ItemPoJo.class);
                    List<Long> values = JSONArray.parseArray(JSON.toJSONString(value),Long.class);
                    Map<Object, String> itemMap = itemPoJos.stream().collect(Collectors.toMap(ItemPoJo::getValue, ItemPoJo::getText));
                    if(CollectionUtils.isNotEmpty(values)){
                        for(Long comboValue : values){
                            String comboText = itemMap.getOrDefault(comboValue.toString(), "");
                            nameIn.add(comboText);
                        }
                    }
                    data = StringUtils.join(nameIn, "，");
                } else {
                    data = StringUtils.join(dataArr, "，");
                }

            } catch (Exception e) {
                data = "";
            }
            if(attrName != null){
                if(data != null){
                    conditionStr.append(attrName).append(mark).append(data).append(";");
                } else {
                    conditionStr.append(attrName).append(mark).append(";");
                }
            } else {
                conditionStr.append(mark).append(data).append(";");
            }
        }
        return conditionStr.toString();
    }


    /**
     * 获取触发条件拼接的日志信息
     * @param ruleValueArr
     * @param businessType
     * @param corpid
     * @return
     */
    public String triggerScreenCondition(JSONArray ruleValueArr, Integer businessType,String corpid){
        // 符号
        String mark = "";
        // 数据
        String data = "";
        StringBuilder conditionStr = new StringBuilder();
        if (CollectionUtils.isEmpty(ruleValueArr)){
            return "";
        }
        for(Object rule : ruleValueArr){
            Integer chooseType = 0;
            String triggerName = "定时退回";
            JSONObject ruleValueJson = (JSONObject) rule;
            JSONObject triggerScreen = FastJsonHelper.getJsonObjectOrDefault(ruleValueJson, SeniorRuleValueEnum.TRIGGER_SCREEN.getAlias(), new JSONObject());
            JSONArray triggerScreenArr  = FastJsonHelper.getJsonArrayOrDefault(triggerScreen, "rule", new JSONArray());
            Integer triggerType = FastJsonHelper.getIntegerOrDefault(triggerScreen, "triggerType",0);
            if(Objects.equals(triggerType,BasicConstant.TWO)){
                triggerName = "当日退回";
                conditionStr.append(triggerName).append("；");
                continue;
            }

            for(Object o : triggerScreenArr){
                JSONObject jsonObject = (JSONObject) o;
                Integer value = jsonObject.getInteger("value");
                chooseType = jsonObject.getInteger("chooseType");
                JSONArray userArr = FastJsonHelper.getJsonArrayOrDefault(jsonObject, "users", new JSONArray());
                JSONArray deptArr = FastJsonHelper.getJsonArrayOrDefault(jsonObject, "depts", new JSONArray());
                JSONArray roleArr = FastJsonHelper.getJsonArrayOrDefault(jsonObject, "roles", new JSONArray());
                List<String> userIdList = JSON.parseArray(userArr.toJSONString(), String.class);
                List<UserEntity> userEntities = userModel.getByUserId(userIdList, corpid);
                List<Long> deptIds = JSON.parseArray(deptArr.toJSONString(), Long.class);
                List<DepartmentEntity> deptEntitys = departmentModel.getByDepIdIn(corpid, deptIds);
                List<Integer> roleIds = JSON.parseArray(roleArr.toJSONString(), Integer.class);
                List<RoleEntity> roleEntities = roleModel.getByRoleIdIn(corpid, roleIds);
                if (CollectionUtils.isEmpty(userEntities) && CollectionUtils.isEmpty(deptEntitys) && CollectionUtils.isEmpty(roleEntities)){
                    data = "所有员工";
                }else {
                    List<String> nameIn = new ArrayList<>();
                    userEntities.forEach(item -> nameIn.add(item.getName()));
                    deptEntitys.forEach(item -> nameIn.add(item.getName()));
                    roleEntities.forEach(item -> nameIn.add(item.getRoleName()));
                    data = StringUtils.join(nameIn, "，");
                }
                if(data != null){
                    conditionStr.append(data).append(value + "天");
                }
            }
            String chooseName = CustomerSeniorBackChildEnum.getNameByCode(chooseType);
            if(Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
                chooseName = ClueSeniorBackChildEnum.getNameByCode(chooseType);
            }
            conditionStr.append(chooseName + "，").append(triggerName).append(";");
        }

        return conditionStr.toString();
    }



    /**
     * 获取分组管理员或成员
     */
    String getPublicGroupAdminUsers(JSONArray jsonArray){
        if (CollectionUtils.isNotEmpty(jsonArray)){
            List<String> names = new ArrayList<>();
            for (Object o : jsonArray){
                JSONObject jsonObject = (JSONObject) o;
                String name = jsonObject.getString("name");
                names.add(name);
            }
           return  StringUtils.join(names, "，");
        }
        return "";
    }
}
